#!/usr/bin/env python3

import pendulum
import os
import sys
sys.path.append(f'{os.path.dirname(os.path.realpath(__file__))}/../utils')
sys.path.append(f'{os.path.dirname(os.path.realpath(__file__))}/../operators')
import wrf_operators as wrf
from utils import cmd_args, cli, parse_config, submit_job

args = cmd_args()

config = parse_config(args.config_json)

if args.start_time:
	config['custom']['start_time'] = args.start_time
else:
	args.start_time = config['custom']['start_time']

def run_genbe(work_root, config, args):
	os.environ['RUN_GEN_BE_STAGE0'] = 'true'
	os.environ['RUN_GEN_BE_STAGE1'] = 'true'
	os.environ['RUN_GEN_BE_STAGE2'] = 'true'
	os.environ['RUN_GEN_BE_STAGE3'] = 'true'
	os.environ['RUN_GEN_BE_STAGE4'] = 'true'
	os.environ['RUN_GEN_BE_DIAGS' ] = 'true'
	os.environ['GEN_BE_DIR'] = args.genbe_root
	os.environ['START_DATE'] = args.start_time.format('YYYYMMDDHH')
	os.environ['END_DATE'] = args.start_time.add(days=config['custom']['be']['run_days']).format('YYYYMMDDHH')
	os.environ['NUM_LEVELS'] = str(config['domains']['e_vert'][0] - 1)
	os.environ['FC_DIR'] = args.work_root
	os.environ['RUN_DIR'] = work_root + '/gen_be/rundir'
	os.environ['WORK_DIR'] = work_root + '/gen_be/workdir'
	os.environ['DOMAIN'] = '01'
	os.environ['INTERVAL'] = str(int(config['time_control']['history_interval'][0] / 60))
	os.environ['STRIDE'] = '4'
	os.environ['FCST_RANGE'] = str(config['custom']['forecast_hours'])
	os.environ['FCST_RANGE1'] = str(config['custom']['forecast_hours'])
	os.environ['FCST_RANGE2'] = '12'
	os.environ['BE_METHOD'] = 'NMC'
	os.environ['NE'] = '1'

	submit_job(f'{args.genbe_root}/scripts/gen_be.ksh', args.np, config, args, wait=True, exclusive=True)

run_genbe(args.work_root, config, args)
